package leetcodev1.字符串;

import leetcodev1.链表.Solution;

import java.util.HashMap;
import java.util.Map;

public class LeetCode8 {
    //将字符串转换成32位的有符号整数
    public int myAtoi(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        s = s.trim();
        int ret = 0, length = s.length(), symbol = 1, coefficient = 1;
        if (s.charAt(0) == '-') {
            symbol = -1;
        }
        for (int i = length - 1; i >= 0; i--) {
            char c = s.charAt(i);
            if (c >= '0' && c <= '9') {
                ret += coefficient * (c - '0');
                coefficient *= 10;
            }
        }
        return symbol * ret;
    }
}

class Answer8{
    //自动机
    public int myAtoi(String str) {
        Automaton automaton = new Automaton();
        int length = str.length();
        //正向处理
        for (int i = 0; i < length; ++i) {
            automaton.get(str.charAt(i));
        }
        return (int) (automaton.sign * automaton.ans);
    }
}
//状态机
//可以用状态模式优化 只考虑当前状态下的操作 状态间转换
//4种状态 4种操作toStart toEnd toSigned toNumber
class Automaton {
    public int sign = 1;
    public long ans = 0;
    private String state = "start";
    private Map<String, String[]> table = new HashMap<String, String[]>() {{
        put("start", new String[]{"start", "signed", "in_number", "end"});
        put("signed", new String[]{"end", "end", "in_number", "end"});
        put("in_number", new String[]{"end", "end", "in_number", "end"});
        put("end", new String[]{"end", "end", "end", "end"});
    }};

    public void get(char c) {
        state = table.get(state)[get_col(c)];
        if ("in_number".equals(state)) {
            ans = ans * 10 + c - '0';
            ans = sign == 1 ? Math.min(ans, (long) Integer.MAX_VALUE) : Math.min(ans, -(long) Integer.MIN_VALUE);
        } else if ("signed".equals(state)) {
            sign = c == '+' ? 1 : -1;
        }
    }

    private int get_col(char c) {
        if (c == ' ') {
            return 0;
        }
        if (c == '+' || c == '-') {
            return 1;
        }
        //可以用这个api，更优雅一点
        if (Character.isDigit(c)) {
            return 2;
        }
        return 3;
    }
}
